<!-- Training_Feedback.vue -->
<template>
  <div class="training-container">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">培训管理</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="请输入学员姓名或教练姓名"
              style="width: 220px; margin-right: 15px;"
              clearable
              @input="debouncedSearch"
              @clear="fetchTrainings"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="statusFilter"
              placeholder="请选择状态"
              style="width: 130px; margin-right: 15px;"
              @change="handleStatusFilterChange"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="已安排" value="SCHEDULED"></el-option>
              <el-option label="已完成" value="COMPLETED"></el-option>
              <el-option label="未通过" value="MISSED"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredTrainings"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="student_name" label="学员姓名" min-width="100" />
        <el-table-column prop="coach_name" label="教练姓名" min-width="100" />
        <el-table-column prop="program_name" label="培训项目" min-width="120" />
        <el-table-column prop="start_time_formatted" label="开始时间" min-width="150" />
        <el-table-column prop="end_time_formatted" label="结束时间" min-width="150" />
        <el-table-column prop="status_text" label="状态" min-width="90">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'SCHEDULED' ? 'warning' :
                     scope.row.status === 'COMPLETED' ? 'success' :
                     scope.row.status === 'CANCELED' ? 'danger' : 'info'">
              {{ scope.row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" min-width="80">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="feedback" label="反馈内容" min-width="150">
          <template #default="scope">
            <div class="content-preview">
              <span>{{ truncateText(scope.row.feedback, 15) }}</span>
              <el-button v-if="scope.row.feedback && scope.row.feedback.length > 15"
                         type="text"
                         @click="showFullContent('反馈内容', scope.row.feedback)">
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-cell">
              <el-button size="small" type="primary" @click="viewTraining(scope.row)">查看</el-button>
              <el-button size="small" type="danger" @click="deleteTraining(scope.row.training_id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <el-dialog v-model="viewDialogVisible" title="查看培训详情" width="50%" top="5vh">
      <el-form :model="viewForm" label-width="120px" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学员">
              <el-select v-model="viewForm.student_id" style="width: 100%">
                <el-option v-for="student in students" :key="student.student_id" :label="student.fullname" :value="student.student_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教练">
              <el-select v-model="viewForm.coach_id" style="width: 100%">
                <el-option v-for="coach in coaches" :key="coach.coach_id" :label="coach.fullname" :value="coach.coach_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="培训项目">
              <el-select v-model="viewForm.program_id" style="width: 100%">
                <el-option v-for="program in programs" :key="program.program_id" :label="program.name" :value="program.program_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="viewForm.status" style="width: 100%">
                <el-option label="已安排" value="SCHEDULED" />
                <el-option label="已完成" value="COMPLETED" />
                <el-option label="已取消" value="CANCELED" />
                <el-option label="未通过" value="MISSED" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="viewForm.start_time"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="viewForm.end_time"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="评分">
          <el-rate v-model="viewForm.rating" :max="5" />
        </el-form-item>

        <el-form-item label="反馈内容">
          <el-input
            v-model="viewForm.feedback"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="培训内容">
          <el-input
            v-model="viewForm.content"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="回复内容">
          <el-input
            v-model="viewForm.response"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看完整内容的对话框 -->
    <el-dialog v-model="contentDialogVisible" :title="contentDialogTitle" width="50%" top="10vh">
      <el-input
        v-model="fullContent"
        type="textarea"
        :rows="10"
        readonly
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="contentDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import requestUtil from '@/util/request.js';
import debounce from 'lodash/debounce';

// 数据相关
const trainings = ref([]);
const students = ref([]);
const coaches = ref([]);
const programs = ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const statusFilter = ref(''); // 状态筛选条件

// 表单相关
const viewDialogVisible = ref(false);
const viewForm = ref({
  training_id: null,
  student_id: null,
  coach_id: null,
  program_id: null,
  start_time: '',
  end_time: '',
  status: 'SCHEDULED',
  rating: 5,
  feedback: '',
  content: '',
  response: ''
});

// 查看完整内容的对话框相关变量
const contentDialogVisible = ref(false);
const contentDialogTitle = ref('');
const fullContent = ref('');

// 工具函数
const truncateText = (text, length) => {
  if (!text) return '';
  return text.length > length ? text.substring(0, length) + '...' : text;
};

// 格式化时间显示
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';

  try {
    const date = new Date(dateTimeString);
    if (isNaN(date.getTime())) return dateTimeString;

    // 格式化为 "YYYY-MM-DD HH:mm"
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    return dateTimeString;
  }
};

// 状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    'SCHEDULED': '已安排',
    'COMPLETED': '已完成',
    'CANCELED': '已取消',
    'MISSED': '未通过'
  };
  return statusMap[status] || status;
};

// 显示完整内容
const showFullContent = (title, content) => {
  contentDialogTitle.value = title;
  fullContent.value = content;
  contentDialogVisible.value = true;
};

// 数据获取函数
const fetchPrograms = async () => {
  try {
    const res = await requestUtil.get('/program/msg', {
      page: 1,
      page_size: 100
    });

    if (res.data?.status === 200) {
      programs.value = res.data.data || [];
    } else {
      programs.value = [];
      ElMessage.error('获取培训项目失败: ' + (res.data?.message || '未知错误'));
    }
  } catch (error) {
    if (error.response?.status === 422) {
      try {
        const res = await requestUtil.get('/program/msg');
        if (res.data?.status === 200) {
          programs.value = res.data.data || [];
        }
      } catch (fallbackError) {
        programs.value = [];
        ElMessage.error('获取培训项目失败: ' + (fallbackError.response?.data?.message || fallbackError.message));
      }
    } else {
      programs.value = [];
      ElMessage.error('获取培训项目异常: ' + (error.response?.data?.message || error.message));
    }
  }
};

const fetchStudents = async () => {
  const res = await requestUtil.get('/student/msg');
  if (res.data?.status === 200) {
    students.value = res.data.data;
  }
};

const fetchCoaches = async () => {
  const res = await requestUtil.get('/coach/msg');
  if (res.data?.status === 200) {
    coaches.value = res.data.data;
  }
};

const fetchTrainings = async () => {
  const res = await requestUtil.get('/student_training/trainings', {
    page: currentPage.value,
    page_size: pageSize.value
  });

  if (res.data?.status === 200) {
    // 根据状态筛选条件过滤数据
    let filteredData = res.data.data;

    // 如果选择了状态筛选条件，则进行筛选
    if (statusFilter.value) {
      filteredData = filteredData.filter(training => training.status === statusFilter.value);
    } else {
      // 如果没有选择筛选条件，默认只显示已安排/已完成/未通过的培训
      filteredData = filteredData.filter(training =>
        training.status === 'SCHEDULED' || training.status === 'COMPLETED'|| training.status === 'MISSED'
      );
    }

    trainings.value = filteredData.map(training => {
      const student = students.value.find(s => s.student_id === training.student_id);
      const coach = coaches.value.find(c => c.coach_id === training.coach_id);
      const program = programs.value.find(p => p.program_id === training.program_id);
      return {
        ...training,
        rating: training.rating && training.rating >= 1 && training.rating <= 5 ?
                Number(training.rating) : 5,
        student_name: student?.fullname || '未知学员',
        coach_name: coach?.fullname || '未知教练',
        program_name: program?.name || '未知项目',
        start_time_formatted: formatDateTime(training.start_time),
        end_time_formatted: formatDateTime(training.end_time),
        status_text: getStatusText(training.status) // 添加中文状态文本
      };
    });
    total.value = res.data.total || 0;
  }
};

// 搜索相关
const filteredTrainings = computed(() => {
  if (!searchQuery.value.trim()) return trainings.value;
  return trainings.value.filter(training =>
    training.student_name.includes(searchQuery.value) ||
    training.coach_name.includes(searchQuery.value)
  );
});

const debouncedSearch = debounce(fetchTrainings, 300);

// 分页相关
const handleSizeChange = size => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchTrainings();
};

const handleCurrentChange = page => {
  currentPage.value = page;
  fetchTrainings();
};

// 状态筛选变化处理
const handleStatusFilterChange = () => {
  currentPage.value = 1; // 重置到第一页
  fetchTrainings();
};

// 表单操作
const viewTraining = (row) => {
  viewForm.value = {
    ...row,
    rating: row.rating && row.rating >= 1 && row.rating <= 5 ?
            Number(row.rating) : 5
  };
  viewDialogVisible.value = true;
};

const deleteTraining = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个培训吗？此操作不可恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const res = await requestUtil.del(`/student_training/trainings/delete/${id}`);
    if (res.data?.status === 200) {
      ElMessage.success('删除成功');
      await fetchTrainings();
    } else {
      ElMessage.error(res.data?.message || '删除失败');
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消删除');
      return;
    }
    ElMessage.error(error.response?.data?.message || '删除失败');
  }
};

// 生命周期
onMounted(async () => {
  await Promise.all([fetchStudents(), fetchCoaches(), fetchPrograms()]);
  await fetchTrainings();
});
</script>

<style scoped>
.training-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  align-items: center;
}

.operation-cell {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.operation-cell .el-button {
  margin-right: 5px;
}

.operation-cell .el-button:last-child {
  margin-right: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.content-preview {
  display: flex;
  align-items: center;
}

.content-preview span {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style>
